package com.pay.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.pay.config.AlipayConfig;
import com.pay.pojo.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;

@Controller
public class PayController {
    @Autowired
    private HttpServletResponse httpResponse;
    @PostMapping("/alipay")
//    请求的数据用实体类来接收
    public void alipay(OrderInfo orderinfo) throws Exception{
        //AlipayClient对象中的参数在AlipayConfig中写好了
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, AlipayConfig.FORMAT, AlipayConfig.charset, AlipayConfig.alipay_public_key,AlipayConfig.sign_type);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(orderinfo.getOid());
        model.setSubject(orderinfo.getSubject());
        model.setTotalAmount(orderinfo.getTotal()+"");
        model.setBody(orderinfo.getDesc());
        model.setProductCode(orderinfo.getProductNo());
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);
        AlipayTradeWapPayResponse alipayTradeWapPayResponse = client.pageExecute(alipay_request);
        String form = alipayTradeWapPayResponse.getBody();
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.charset);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}